<template>
  <div>
    <template v-if="url">
      <iframe :src="url" frameborder="0" width="100%;" :height="previewHeight"></iframe>
    </template>
    <template v-else>
      <div
        v-if="loading"
        v-loading="loading"
        element-loading-text="加载中"
        element-loading-spinner="el-icon-loading"
        style="height: 4rem;"
      ></div>
      <div v-else class="easy-container p-x-16 bg-fafafa info">
        当前不支持在线显示此种类型的文件
      </div>
    </template>
  </div>
</template>

<script>
const w = ['doc', 'docx', 'txt'];
const s = ['xls', 'xlsx'];
const p = ['ppt', 'pptx'];
const f = ['pdf'];

const defaultHeight = {
  w: '880px',
  s: '600px',
  p: '600px',
  f: '880px',
};

export default {
  name: 'yozo-preview',
  props: {
    file: Object,
  },
  data() {
    return {
      loading: false,
      url: '',
    };
  },
  computed: {
    fileUrl() { return `https://file.learnerhub.net/${this.file.key}`; },
    fileType() {
      const fileSuffix = this.file.ext;
      if (w.includes(fileSuffix)) return 'w';
      else if (s.includes(fileSuffix)) return 's';
      else if (p.includes(fileSuffix)) return 'p';
      else if (f.includes(fileSuffix)) return 'f';
      return undefined;
    },
    previewHeight() {
      return defaultHeight[this.fileType];
    },
  },
  created() {
    if (this.fileType) this.getYozoPreviewUrl();
  },
  methods: {
    getYozoPreviewUrl() {
      this.loading = true;
      this.$api.other.getYozoPreview({ url: this.fileUrl })
        .then((res) => { this.url = res.data.data; })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
};
</script>

<style></style>
